﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections;
using System.Web;
using System.IO;
using System.Web.UI;
using Utils.DC.Web.UI;
using System.Web.Mail;
using Utils.DCSControl;
using Utils.Entity;
using System.Web.SessionState;


namespace Utils
{
    public class ActionName
    {

        public string NEW
        {
            get
            {
                return "New";
            }
        }

        public string NOT_NEW
        {
            get
            {
                return "NotNew";
            }
        }

        public string TYPICAL
        {
            get
            {
                return "Typical";
            }
        }

        public string NOT_TYPICAL
        {
            get
            {
                return "NotTypical";
            }
        }

        public string HOT
        {
            get
            {
                return "Hot";
            }
        }

        public string NOT_HOT
        {
            get
            {
                return "NotHot";
            }
        }

        public string APPROVED
        {
            get
            {
                return "Approved";
            }
        }

        public string NOT_APPROVED
        {
            get
            {
                return "NotApproved";
            }
        }

        public string PROMOTION
        {
            get
            {
                return "Promotion";
            }
        }

        public string NOT_PROMOTION
        {
            get
            {
                return "NotPromotion";
            }
        }

        public string BEST_SELLER
        {
            get
            {
                return "BestSeller";
            }
        }

        public string NOT_BEST_SELLER
        {
            get
            {
                return "NotBestSeller";
            }
        }

        public string WEEKLY_PRODUCT
        {
            get
            {
                return "WeeklyProduct";
            }
        }

        public string NOT_WEEKLY_PRODUCT
        {
            get
            {
                return "NotWeeklyProduct";
            }
        }
    }

    public class MailEntity
    {
        MailMessage mail = new MailMessage();

        public MailEntity()
        {
        }

        public MailEntity(string from, string to, string subject, string body, bool isHTML)
        {
            mail.From = from;
            mail.To = to;
            mail.Subject = subject;
            mail.Body = body;

            mail.BodyFormat = isHTML?MailFormat.Html:MailFormat.Text;
        }

        public string From
        {
            get{ return mail.From;}
            set{ mail.From = value;}
        }

        public string To
        {
            get{ return mail.To;}
            set{ mail.To = value;}
        }

        public string Subject
        {
            get{ return mail.Subject;}
            set{ mail.Subject = value;}
        }

        public string Body
        {
            get{ return mail.Body;}
            set{ mail.Body = value;}
        }

        public bool IsHTML
        {
            get{return mail.BodyFormat == MailFormat.Html?true:false;}
            set{ mail.BodyFormat = value?MailFormat.Html:MailFormat.Text; }
        }

        /// <summary>
        /// Hàm dùng để send mail
        /// </summary>
        /// <param name="userName">Tài khoản dùng để đăng nhập hệ thống mail</param>
        /// <param name="password">Password của tài khoản trên</param>
        /// <param name="smtpServer">Địa chỉ của server</param>
        public void Send(string userName, string password, string smtpServer)
        {
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");	//basic authentication
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", userName); //set your username here
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", password);	//set your password here
            SmtpMail.SmtpServer = smtpServer;
            SmtpMail.Send(mail);
        }
    }

    public class Common
    {
        public static void Alert(HttpRequest request, HttpResponse response, int result, string messageOk, string messageError)
        {
            try
            {
                string redirectUrl = "";
                if (request.UrlReferrer != null)
                {
                    redirectUrl = request.UrlReferrer.ToString();
                }
                else
                {
                    redirectUrl = "/";
                }
                if (result > 0)
                {
                    response.Write("<script>alert('" + messageOk + "'); window.location. href = '" + redirectUrl + "'</script>");
                }
                else
                {
                    response.Write("<script>alert('" + messageError + "'); window.location. href = '" + redirectUrl + "'</script>");
                }
            }
            catch(Exception ex)
            {
                response.Redirect("/", true);
            }
        }

        /// <summary>
        /// Ghi lỗi của tiến trình ra 1 file để quản lý lỗi trong quá trình thực hiện thao tác
        /// </summary>
        /// <param name="ExceptionString">Nội dung lỗi xảy ra</param>
        public static void FileWriter(string ExceptionString)
        {
            try
            {
                string ErrDate = DateTime.Now.Minute + "." + DateTime.Now.Hour + "." + DateTime.Now.Day + "." + DateTime.Now.Month + "." + DateTime.Now.Year;
                if (!File.Exists(HttpContext.Current.Server.MapPath("~/Upload/Error.txt")))
                {
                    TextWriter tsw = new StreamWriter(HttpContext.Current.Server.MapPath("~/Upload/Error.txt"));
                    //Writing text to the file.
                    tsw.WriteLine(ErrDate + "----" + ExceptionString);
                    //Close the file.                
                    tsw.Close();
                }
                StreamWriter SW;
                SW = File.AppendText(HttpContext.Current.Server.MapPath("~/Upload/Error.txt"));
                SW.WriteLine(ErrDate + "----" + ExceptionString);
                SW.Close();
            }
            catch (Exception e)
            {

            }
        }

        public static void GetRadomPassword(int numberOfCharater, ref string decodePassword, ref string encodePassword)
        {
            decodePassword = "";
            Random random = new Random();
            for (int i = 0; i < numberOfCharater; i++)
            {
                decodePassword += random.Next(0, 9).ToString();
            }

            encodePassword = Security.Encrypt(decodePassword);
        }

        public static void ExportExcel(String fileName, HttpResponse Response, System.Web.UI.WebControls.Repeater repeater)
        {
            string attachment = "attachment; filename=" + fileName + ".xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/ms-excel";
            StringWriter sw = new StringWriter();
            System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
            repeater.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }

        public static void ExportExcel(String fileName, HttpResponse Response, System.Web.UI.WebControls.DataList dataList)
        {
            string attachment = "attachment; filename=" + fileName + ".xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/ms-excel";
            StringWriter sw = new StringWriter();
            System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
            dataList.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }

        public static bool CheckLogin(UserControl control)
        {
            if (((dcPage)control.Page).CurrentUser != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool CheckVip(UserControl control)
        {
            UserEntity user = ((dcPage)control.Page).CurrentUser;
            if (user != null && user.UserType == (byte)Common.USER_TYPE.VIP && user.ExpireDate != null)
            {
                if (((DateTime)user.ExpireDate - DateTime.Now).TotalSeconds > 0)
                {
                    return true;
                }
            }
            return false;
        }

        public static bool CheckVip(HttpSessionState session)
        {
            UserEntity user = (UserEntity)session[PageUtility.SESSION_USER_NAME];
            if (user != null && user.UserType == (byte)Common.USER_TYPE.VIP && user.ExpireDate != null)
            {
                if (((DateTime)user.ExpireDate - DateTime.Now).TotalSeconds > 0)
                {
                    return true;
                }
            }
            return false;
        }

        public static ActionName ACTION_NAME = new ActionName();

        public enum MAMCAU_TYPE { Lo = (byte)1, DeTong = (byte)2, DeLap = 3 };

        public enum CAU_TYPE { CAU_XUOI = (byte)1, CAU_NGUOC = (byte)2, TAT_CA = (byte)3, CHUA_XAC_DINH = (byte)0 };

        public static string Conn
        {
            get
            {

                //return Security.Decode("ylBEgZmhIpuDWHVngHJXiG0TI4Co402gq2GPDWsTPCmQI5GgWbORSJe3BWKOX4AUGtiOM8VITGrjqxXlgLg7QQHKKu8t86AQ");
                //return ConfigurationManager.ConnectionStrings["DCSConnectionString"].ConnectionString;
                return Security.Decode(ConfigurationManager.ConnectionStrings["DCSConnectionString"].ConnectionString);
                //return Security.Decode("ROKhdpoPOWeHr6O1L0f6y/BJh87MKOPtc/05mko7lXMp3h36hiK4Curz35K4PwoKa6gdmyQEI+ywcqrP8HOJpVBA92QSBoMeFRrH0EfECG8=");
            }
        }

        public static string ImageType
        {
            get
            {
                return ConfigurationManager.AppSettings["ImageType"];
            }
        }
        
        //public enum ACTION_NAME
        //{
        //    NEW = "New", NOT_NEW = "NotNew", TYPICAL = "Typical", NOT_TYPICAL = "NotTypical",
        //    HOT = "Hot", NOT_HOT = "NotHot", APPROVED = "Approved", NOT_APPROVED = "NotApproved",
        //    PROMOTION = "Promotion", NOT_PROMOTION = "NotPromotion", BEST_SELLER = "BestSeller",
        //    NOT_BEST_SELLER = "NotBestSeller", WEEKLY_PRODUCT = "WeeklyProduct", NOT_WEEKLY_PRODUCT = "NotWeeklyProduct"
        //};

        public static string[] BoSo
        {
                get
                {
                    return new string[]{"00,11,22,33,44,55,66,77,88,99",
                    "01,10,06,60,56,65,15,51,12,21,17,71,62,26,67,76,23,32,28,82,73,37,78,87,34,43,39,93,84,48,89,98,40,04,45,54,90,09,95,59",
                    "02,20,70,07,52,25,57,75,13,31,18,81,63,36,68,86,24,42,29,92,74,47,79,97,30,03,35,53,80,08,85,58",
                    "05,50,16,61,27,72,38,83,49,94",
                    "01,10,21,12,23,32,34,43,56,65,67,76,78,87,89,98",
                    "07,70,17,71,27,72,37,73,47,74,25,52,26,62,28,82,29,92",
                    "34,43,53,35,37,73,39,93,45,54,47,74,49,94,57,75,59,95,79,97",
                    "06,60,07,70,08,80,09,90,17,71,18,81,19,91,28,82,29,92,39,93",
                    "12,21,18,81,23,32,27,72,28,82,29,92,37,73,38,83,39,93,78,87,79,97,89,98",
                    "04,40,06,60,07,70,14,41,15,51,17,71,24,42,26,62,48,84,39,93,58,85,59,95",
                    "33,34,35,36,37,38,43,44,45,46,47,48,53,54,55,56,57,58,63,64,65,66,67,68,73,74,75,76,77,78,83,84,85,86,87,88",
                    "03,30,08,80,53,35,58,85,14,41,69,96,19,91,64,46"
                    };
                }
        }

        public enum USER_TYPE { NotSet = (byte)0, User = (byte)1, VIP = (byte)4, Admin = (byte)2, SuperAdmin = (byte)3 };

        /// <summary>
        /// Ham Lấy về số ngày trong tuần dựa theo tham số truyền vào
        /// </summary>
        /// <param name="dayOfWeek"></param>
        /// <returns></returns>
        public static int GetDayOfWeek(DayOfWeek dayOfWeek)
        {
            switch (dayOfWeek.ToString())
            {
                case "Sunday":
                    return 8;
                case "Monday":
                    return 2;
                case "Tuesday":
                    return 3;
                case "Wednesday":
                    return 4;
                case "Thursday":
                    return 5;
                case "Friday":
                    return 6;
                case "Saturday":
                    return 7;
            }
            return -1;
        }

        public static String GetDayOfWeekString(DayOfWeek dayOfWeek)
        {
            switch (dayOfWeek.ToString())
            {
                case "Sunday":
                    return "Chủ Nhật";
                case "Monday":
                    return "Thứ Hai";
                case "Tuesday":
                    return "Thứ Ba";
                case "Wednesday":
                    return "Thứ Tư";
                case "Thursday":
                    return "Thứ Năm";
                case "Friday":
                    return "Thứ Sáu";
                case "Saturday":
                    return "Thứ Bảy";
            }
            return "";
        }

        /// <summary>
        /// Lấy về số ngày trong tuần là ngày hiện tại
        /// </summary>
        /// <returns></returns>
        public static int GetDayOfWeek()
        {
            DayOfWeek d = DateTime.Now.DayOfWeek;
            switch (d.ToString())
            {
                case "Sunday":
                    return 8;
                case "Monday":
                    return 2;
                case "Tuesday":
                    return 3;
                case "Wednesday":
                    return 4;
                case "Thursday":
                    return 5;
                case "Friday":
                    return 6;
                case "Saturday":
                    return 7;
            }
            return -1;
        }
    }

    public class Format
    {
        public static String FormatVietNameDate(DateTime date)
        {
            return date.Day + "/" + date.Month + "/" + date.Year;
        }

        public static String FormatVietNameDateSQLSyntax(DateTime date)
        {
            return date.Year + "-" + date.Month + "-" + date.Day;
        }

        public static String FormatVietNameDateTimeSQLSyntax(DateTime date)
        {
            return date.Year + "-" + date.Month + "-" + date.Day + " " + date.Hour + ":" + date.Minute + ":" + date.Second;
        }

        public static String FormatVietNameDateTime(DateTime date)
        {
            return date.Day + "/" + date.Month + "/" + date.Year + "  " + date.Hour + ":" + date.Minute;
        }

        public static DateTime ConvertFromVietNameDate(string date)
        {
            try
            {
                string[] strs = date.Split(new char[]{'/'});
                return new DateTime(date[2],date[1],date[0]);
            }
            catch (Exception e)
            {
                return DateTime.Now;
            }
        }
        public static string ConvertToNoSign(string pagename)
        {
            int n = 0;
            if (pagename != null && pagename.Trim() != "")
            {
                pagename = pagename.Trim();
                pagename = pagename.ToLower();
                n = pagename.Length;
                if (n > 250)
                {
                    pagename = pagename.Substring(0, 250);
                    n = pagename.Length;
                }
                string[] NewPagename = new string[n];

                string Page = "";

                for (int i = 0; i < n; i++)
                {
                    NewPagename[i] = pagename.Substring(i, 1);
                    switch (NewPagename[i])
                    {
                        case " ":
                            NewPagename[i] = "-";
                            break;
                        case "~":
                            NewPagename[i] = "-";
                            break;
                        case ":":
                            NewPagename[i] = "-";
                            break;
                        case "^":
                            NewPagename[i] = "-";
                            break;
                        case "%":
                            NewPagename[i] = "-";
                            break;
                        case "à":
                            NewPagename[i] = "a";
                            break;
                        case "#":
                            NewPagename[i] = "-";
                            break;
                        case "ả":
                            NewPagename[i] = "a";
                            break;
                        case "ã":
                            NewPagename[i] = "a";
                            break;
                        case "á":
                            NewPagename[i] = "a";
                            break;
                        case "ạ":
                            NewPagename[i] = "a";
                            break;
                        case "ă":
                            NewPagename[i] = "a";
                            break;
                        case "ằ":
                            NewPagename[i] = "a";
                            break;
                        case "-":
                            NewPagename[i] = "-";
                            break;
                        case "ẳ":
                            NewPagename[i] = "a";
                            break;
                        case "ẵ":
                            NewPagename[i] = "a";
                            break;
                        case "ắ":
                            NewPagename[i] = "a";
                            break;
                        case "ặ":
                            NewPagename[i] = "a";
                            break;
                        case "â":
                            NewPagename[i] = "a";
                            break;
                        case "ầ":
                            NewPagename[i] = "a";
                            break;
                        case "ẩ":
                            NewPagename[i] = "a";
                            break;
                        case "ẫ":
                            NewPagename[i] = "a";
                            break;
                        case "ấ":
                            NewPagename[i] = "a";
                            break;
                        case "ậ":
                            NewPagename[i] = "a";
                            break;
                        case "è":
                            NewPagename[i] = "e";
                            break;
                        case "ẻ":
                            NewPagename[i] = "e";
                            break;
                        case "ẽ":
                            NewPagename[i] = "e";
                            break;
                        case "é":
                            NewPagename[i] = "e";
                            break;
                        case "ẹ":
                            NewPagename[i] = "e";
                            break;
                        case "ê":
                            NewPagename[i] = "e";
                            break;
                        case "ề":
                            NewPagename[i] = "e";
                            break;
                        case "ể":
                            NewPagename[i] = "e";
                            break;
                        case "ễ":
                            NewPagename[i] = "e";
                            break;
                        case "ế":
                            NewPagename[i] = "e";
                            break;
                        case "ệ":
                            NewPagename[i] = "e";
                            break;
                        case "ì":
                            NewPagename[i] = "i";
                            break;
                        case "ỉ":
                            NewPagename[i] = "i";
                            break;
                        case "ĩ":
                            NewPagename[i] = "i";
                            break;
                        case "í":
                            NewPagename[i] = "i";
                            break;
                        case "ị":
                            NewPagename[i] = "i";
                            break;
                        case "ò":
                            NewPagename[i] = "o";
                            break;
                        case "ỏ":
                            NewPagename[i] = "o";
                            break;
                        case "õ":
                            NewPagename[i] = "o";
                            break;
                        case "ó":
                            NewPagename[i] = "o";
                            break;
                        case "ô":
                            NewPagename[i] = "o";
                            break;
                        case "ọ":
                            NewPagename[i] = "o";
                            break;
                        case "ồ":
                            NewPagename[i] = "o";
                            break;
                        case "ổ":
                            NewPagename[i] = "o";
                            break;
                        case "ỗ":
                            NewPagename[i] = "o";
                            break;
                        case "ố":
                            NewPagename[i] = "o";
                            break;
                        case "_":
                            NewPagename[i] = "-";
                            break;
                        case "ộ":
                            NewPagename[i] = "o";
                            break;
                        case "ơ":
                            NewPagename[i] = "o";
                            break;
                        case "ờ":
                            NewPagename[i] = "o";
                            break;
                        case "ở":
                            NewPagename[i] = "o";
                            break;
                        case "ỡ":
                            NewPagename[i] = "o";
                            break;
                        case "ớ":
                            NewPagename[i] = "o";
                            break;
                        case "ợ":
                            NewPagename[i] = "o";
                            break;
                        case "ù":
                            NewPagename[i] = "u";
                            break;
                        case "ủ":
                            NewPagename[i] = "u";
                            break;
                        case "ũ":
                            NewPagename[i] = "u";
                            break;
                        case "ú":
                            NewPagename[i] = "u";
                            break;
                        case "ụ":
                            NewPagename[i] = "u";
                            break;
                        case "ư":
                            NewPagename[i] = "u";
                            break;
                        case "ừ":
                            NewPagename[i] = "u";
                            break;
                        case "ử":
                            NewPagename[i] = "u";
                            break;
                        case "ữ":
                            NewPagename[i] = "u";
                            break;
                        case "ứ":
                            NewPagename[i] = "u";
                            break;
                        case "ự":
                            NewPagename[i] = "u";
                            break;
                        case "ỳ":
                            NewPagename[i] = "y";
                            break;
                        case "ỷ":
                            NewPagename[i] = "y";
                            break;
                        case "ỹ":
                            NewPagename[i] = "y";
                            break;
                        case "ý":
                            NewPagename[i] = "y";
                            break;
                        case "ỵ":
                            NewPagename[i] = "y";
                            break;
                        case "đ":
                            NewPagename[i] = "d";
                            break;
                        case "/":
                            NewPagename[i] = "-";
                            break;
                        case "?":
                            NewPagename[i] = "-";
                            break;
                        case ".":
                            NewPagename[i] = "-";
                            break;
                        case "*":
                            NewPagename[i] = "-";
                            break;
                        case "&":
                            NewPagename[i] = "-";
                            break;
                        case "@":
                            NewPagename[i] = "-";
                            break;
                        case "!":
                            NewPagename[i] = "-";
                            break;
                        case ",":
                            NewPagename[i] = "-";
                            break;
                        case "'":
                            NewPagename[i] = "";
                            break;
                        case "\"":
                            NewPagename[i] = "";
                            break;

                    }
                    Page = Page + NewPagename[i];

                }
                return Page.Replace("---", "-");
            }
            return "";
        }

        
    }

    public class MyMessage
    {
        public static string ReplaceSpecialKey(string Message)
        {
            Message = Message.Replace("'", "");
            Message = Message.Replace("\"", "");
            Message = Message.Replace("\n", "");
            Message = Message.Replace("\r", "");
            return Message;
        }

        public static void ShowError(string message)
        {
            message = ReplaceSpecialKey(message);
            Page mPage = HttpContext.Current.Handler as Page;
            mPage.ClientScript.RegisterStartupScript(typeof(Page), "ShowError", "alert('" + message + "');", true);
        }

        public static void ShowMessage(string message)
        {
            message = ReplaceSpecialKey(message);
            try
            {
                Page mPage = HttpContext.Current.Handler as Page;
                mPage.ClientScript.RegisterStartupScript(typeof(Page), "ShowMessage", "alert('" + message + "');", true);
            }
            catch
            {
            }
        }

        public static void ShowMessage(string message, string newUrl)
        {
            message = ReplaceSpecialKey(message);
            Page mPage = HttpContext.Current.Handler as Page;
            if (newUrl.Length > 1)
            {
                mPage.ClientScript.RegisterStartupScript(typeof(Page), "ShowMessage", "alert('" + mPage.Server.HtmlEncode(message) + "'); location.href='" + newUrl + "';", true);
            }
            else
            {
                ShowMessage(message);
            }
        }
    }
}
